
<script>
// 引出组合式api
import { computed, onBeforeMount, onBeforeUnmount, ref } from "vue";
import { Toast } from "vant";

// pinia状态管理
import { useIndex } from "../stores/index.js";
import { useBookcase } from "../stores/bookcase.js";

// 引入组件
import BookCaseMain from "@/components/BookCase/BookCase";
import HistoryRecord from "@/components/BookCase/HistoryRecord";
import SideLeftMe from "@/components/SideLeftMe";

export default {
  // 引入组件
  setup() {
    // 使用pinia
    const indexStore = useIndex();
    const bookcaseStore = useBookcase();

    // 显示个人中心方法
    let changeSideLeftMeShow = () => {
      console.log("显示");
      indexStore.changeSideLeftMeShow(true);
    };

    // vant3组件
    const showPopover = ref(false);
    const actions = [
      { text: "列表模式", icon: "custom iconfont icon-wuxupailie" },
      { text: "管理书籍", icon: "custom iconfont icon-yingyongguanli" },
    ];

    // 气泡式弹窗触发事件
    let onSelect = (action, index) => {
      if (indexStore.active == 0) {
        if (index == 0) {
          bookcaseStore.changeShow(!bookcaseStore.isFlex);
          action.text = !bookcaseStore.isFlex ? "网格模式" : "列表模式";
        } else if (index == 1) {
          if (!bookcaseStore.isFlex) {
            // 修改状态
            bookcaseStore.changeEdit(true);
            // 得到全部数据数组 服务于全选
            let fullBookChecked = userinfo.value.bookcase.map((o) => o.BookId);
            bookcaseStore.$patch({ fullBookChecked });
          } else Toast("请在列表模式下\n管理书籍");
        }
      } else if (indexStore.active == 1) {
        console.log("浏览历史");
        if (index == 0)
          Toast("您已经在列表模式下\n无需切换") && console.log("弹窗提示内容");
        else if (index == 1) {
          // 修改状态
          bookcaseStore.changeHistoryEdit(true);
          // 得到全部数据数组 服务于全选
          let fullBookChecked = userinfo.value.history.map((o) => o.BookId);
          bookcaseStore.$patch({ fullBookChecked });
        }
      }
    };

    // 取消按钮事件
    let cencalFun = () => {
      if (indexStore.active == 0) bookcaseStore.changeEdit(false);
      else if (indexStore.active == 1) bookcaseStore.changeHistoryEdit(false);
    };

    // 搜索框显示方法
    let searchFlag = ref(false);
    let searchShowFun = () => {
      if (!searchFlag.value) searchFlag.value = true;
      // console.log(searchFlag);
    };

    // 清空输入框
    let clearFun = () => {
      searchFlag.value = false;
      keyword.value = "";
    };

    let searchFun = () => {};

    // 关键字
    let keyword = ref("");

    // 初始化用户对象 默认值 {}
    let userinfo = ref({});

    // 初始化本地存储
    let stroageInit = () => {
      // console.log("stroageInit");
      userinfo.value = JSON.parse(localStorage.getItem("userinfo"));
      console.log("本地所取数据", userinfo.value);
    };

    // 本地存储更新
    let stroageUpdate = () => {
      // console.log("stroageUpdate");
      localStorage.setItem("userinfo", JSON.stringify(userinfo.value));
    };

    // 更新视图
    let updateLocalStorage = () => {
      stroageInit();
    };

    // 全选方法
    let toggleAll = () => {
      bookcaseStore.toggleAll();
    };

    // 删除历史记录方法
    let delFun = () => {
      console.log("触发删除按钮", indexStore.active);
      if (indexStore.active == 0) {
        // 先删除
        let userinfo = JSON.parse(localStorage.getItem("userinfo"));
        userinfo.bookcase = userinfo.bookcase.filter(
          (o) => !bookcaseStore.bookChecked.includes(o.BookId)
        );

        // 后判断 书架首数是否被删除了
        if (
          !userinfo.bookcase.some((item) => item.recent) &&
          userinfo.bookcase.length
        ) {
          userinfo.bookcase[0].recent = true;
        }

        localStorage.setItem("userinfo", JSON.stringify(userinfo));
        // 更新视图
        updateLocalStorage();
        // 退出编辑模式 + 清空选中数据数组 + 清空全数据数组
        bookcaseStore.$patch({
          isHistoryEdit: false,
          bookChecked: [],
          fullBookChecked: [],
        });
      } else if (indexStore.active == 1) {
        let userinfo = JSON.parse(localStorage.getItem("userinfo"));
        userinfo.history = userinfo.history.filter(
          (o) => !bookcaseStore.bookChecked.includes(o.BookId)
        );
        localStorage.setItem("userinfo", JSON.stringify(userinfo));
        // 更新视图
        updateLocalStorage();
        // 退出编辑模式 + 清空选中数据数组 + 清空全数据数组
        bookcaseStore.$patch({
          isHistoryEdit: false,
          bookChecked: [],
          fullBookChecked: [],
        });
      }
      Toast.success("操作成功");
    };

    // 挂载前
    onBeforeMount(() => {
      stroageInit();
    });

    // 卸载前
    onBeforeUnmount(() => {
      stroageUpdate();
    });

    return {
      delFun, // 删除历史记录方法

      toggleAll, // 全选

      // 选中的数据数组
      bookChecked: computed(() => bookcaseStore.bookChecked),

      // 历史记录的删除按钮高亮状态
      historyDelCon: computed(() => bookcaseStore.historyDelCon),

      // 书架的删除按钮高亮状态
      caseDelCon: computed(() => bookcaseStore.caseDelCon),

      // 更新视图
      updateLocalStorage,

      // 用户对象
      userinfo,

      // 关键字
      keyword,

      // 清空输入框
      clearFun,

      searchFun,

      // 搜索框显示方法
      searchFlag,
      searchShowFun,

      // 取消按钮事件
      cencalFun,

      // 气泡式弹窗触发事件
      onSelect,

      // vant3组件
      showPopover,
      actions,

      // 编辑状态
      isEdit_: computed(
        () => bookcaseStore.isEdit || bookcaseStore.isHistoryEdit
      ),

      // 书架 浏览记录 下标
      active: computed({
        get: () => indexStore.active,
        set: (active) => {
          bookcaseStore.$patch({
            isFlex: true,
            isEdit: false,
            isHistoryEdit: false,
          });
          indexStore.$patch({ active });
        },
      }),

      // 个人中心配置
      SideLeftMeShow: computed(() => indexStore.SideLeftMeShow),
      changeSideLeftMeShow,
    };
  },

  components: { BookCaseMain, HistoryRecord, SideLeftMe },
};
</script>

<template>
  <div>
    <div class="BookCase">
      <van-tabs
        v-model:active="active"
        shrink
        animated
        swipeable
        color="#f91337"
        line-width="12px"
        line-height="3px"
        title-active-color="#2b2742"
        title-inactive-color="#666"
      >
        <template #nav-left>
          <div class="item" @click="changeSideLeftMeShow">
            <em
              class="iconfont icon-huli-01"
              :style="{ color: SideLeftMeShow ? '#fe537a' : '#423d5b' }"
            ></em>
            <i class="left"></i><i class="right"></i>
          </div>
        </template>

        <template #nav-right>
          <div class="nav-right" v-if="!isEdit_">
            <div
              :class="['inp', { show: searchFlag }]"
              v-if="active == 0"
              @click="searchShowFun"
            >
              <em class="iconfont icon-31sousuo"></em>
              <input
                @keyup.enter.stop="searchFun"
                v-model="keyword"
                type="text"
                placeholder="所搜之书.."
              />
              <del @click.stop="clearFun" v-if="keyword.length">×</del>
            </div>
            <van-popover
              v-model:show="showPopover"
              :actions="actions"
              placement="bottom-end"
              :show-arrow="true"
              theme="dark"
              @select="onSelect"
              :offset="[12, 0]"
            >
              <template #reference>
                <em class="iconfont icon-liebiao2"></em>
              </template>
            </van-popover>
          </div>
          <div class="nav-right" v-if="isEdit_">
            <button class="toggleAll" @click="toggleAll">
              {{
                bookChecked.length == userinfo.history.length ? "取消" : "全选"
              }}
            </button>
            <button
              :class="['del', { con: historyDelCon || caseDelCon }]"
              @click="delFun"
            >
              移除
            </button>
            <button class="cencal" @click="cencalFun">取消</button>
          </div>
        </template>
        <van-tab title="书架">
          <BookCaseMain
            v-if="userinfo.bookcase.length"
            :userinfo="userinfo"
            :keyword="keyword"
          />
          <div class="emtpy" v-if="!userinfo.bookcase.length">
            <img src="../assets/img/none-book.png" alt="" />
          </div>
        </van-tab>
        <van-tab title="浏览记录">
          <HistoryRecord
            :userinfo="userinfo"
            v-if="userinfo.history.length"
            @updateLocalStorage="updateLocalStorage"
          />
          <div class="emtpy" v-if="!userinfo.history.length">
            <img src="../assets/img/none-content.png" alt="" />
          </div>
        </van-tab>
      </van-tabs>
      <BottomNavigationBar current="0" />
    </div>
    <SideLeftMe />
  </div>
</template>

<style lang="scss" scoped>
.BookCase {
  min-height: 100%;

  ::v-deep .van-tabs {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }

  ::v-deep .van-tabs__wrap {
    height: 50px;
    line-height: 50px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;

    .van-tabs__nav {
      padding: 0 14px 15px;
      .item {
        display: flex;
        align-items: center;
        margin-right: 10px;
        position: relative;
        .iconfont {
          font-size: 24px;
          color: #423d5b;
          transition: all 0.3s ease;
          &:active {
            transform: scale(0.85);
            opacity: 0.7;
          }
        }
        .left,
        .right {
          position: absolute;
          border: 1px solid white;
          width: 0;
          height: 0;
          &.left {
            left: 8px;
          }
          &.right {
            right: 8px;
          }
        }
      }

      .nav-right {
        position: absolute;
        right: 14px;
        top: 0;
        bottom: 15px;
        display: flex;
        align-items: center;

        .iconfont {
          font-weight: bold;
          color: #afb3c2;
          font-size: 18px;

          &.icon-liebiao2 {
            margin-right: 6px;
          }
        }

        .inp {
          height: 32px;
          border-radius: 16px;
          background-color: #f2f6f8;
          display: flex;
          align-items: center;
          padding: 0 12px 0 36px;
          box-sizing: border-box;
          width: 8em;
          margin-right: 16px;
          position: relative;

          // 动画效果
          transition: all 0.3s ease;
          padding: 0 18px;
          width: 0;

          &.show {
            width: 8em;
            padding: 0 12px 0 36px;
            del {
              display: flex;
            }
          }

          .icon-31sousuo {
            font-size: 19px;
            margin-right: 10px;
            display: block;
            position: absolute;
            left: 10px;
          }

          input {
            font-size: 12px;
            padding: 0;
            border: 0;
            display: block;
            width: 100%;
          }

          del {
            color: #afb3c2;
            font-size: 20px;
            text-decoration: none;
            background-color: #d7dbed;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            flex-shrink: 0;
            position: absolute;
            right: 10px;
            top: 0;
            bottom: 0;
            margin: auto;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 8px;
            display: none;
          }
        }

        button {
          padding: 0;
          border: 0;
          background-color: #fff;
          height: 30px;
          display: flex;
          align-items: center;
          line-height: 30px;
          box-sizing: border-box;
          padding: 0 8px;
        }
        .toggleAll {
          font-size: 14px;
        }
        .del {
          font-size: 14px;
          color: #999;
          &.con {
            color: #fa6d7d;
          }
        }
        .cencal {
          font-size: 14px;
          color: #999;
        }
      }

      .van-tab {
        transition: font-size 0.15s ease;
        margin-right: 8px;
        font-weight: bold;
        height: 50px;
        line-height: 50px;

        &:active {
          transform: scale(0.85);
          opacity: 0.7;
        }
        &.van-tab--active {
          transform: scale(1.2);
        }
      }
    }
  }

  ::v-deep .van-tabs__content {
    position: absolute;
    top: 50px;
    bottom: 56px;
    left: 0;
    right: 0;
    overflow-y: scroll;
    overflow-x: hidden;
    .van-swipe {
      height: max-content;
    }
  }

  .emtpy {
    padding-top: 100px;
    img {
      width: 210px;
      margin: 0 auto;
      display: block;
    }
  }
}
</style>